window.addEventListener('load', function (event) {
	login();
	
	ringTone = document.getElementById('ringTone');
	ringBackTone = document.getElementById('ringBackTone');
	ringTone.loop = true;
	
	configCall = {
		audio_remote : document.getElementById('remoteAudio'),
		video_remote : document.getElementById('remoteVideo'),
		video_local : document.getElementById('localVideo'),
		events_listener : { events : '*', listener : eventsSessionListener },
		sip_caps: [
			{ name: '+g.oma.sip-im' },
			{ name: '+sip.ice' },
			{ name: 'language', value: '\"en,fr\"' }
		]
	};
	
	$('#callStatus').val('Aucun appel');
}, false);

window.addEventListener('unload', function (e) {
	logout();
}, false);

var sipStack = null;
var session = null;
var callSession = null;
var sipServerAddress = "10.69.173.4";

var ringBackTone = null;
var ringTone = null;

var configCall = null;

var fullScreen = false;

var eventsListener = function (e) {
	switch (e.type) {
		case 'started' : {
			register();
			break;
		}
		case 'connected' : {
			if (e.session === session) {
				$('#result').val('Vous êtes connecté');
				$('.callCmd').removeAttr('disabled');
			}
			break;
		}
		case 'stopped' : {
			$('#result').val('Vous êtes déconnecté');
			$('.callCmd').attr('disabled', 'true');
			session = null;
			callSession = null;
			sipStack = null;
			break;
		}
		case 'm_permission_accepted' : {
			$('#hangupCmd').removeAttr('disabled');
			$('.callCmd').attr('disabled', 'true');
			break;
		}
		case 'i_new_call' : {
			$('.incomingCallLabel').val(e.newSession.getRemoteFriendlyName() + ' vous appelle');
			//$('#callStatus').slideDown(500);
			if (!callSession) {
				// If we are not in call, create a new audio session.
				callSession = e.newSession;
				callSession.setConfiguration(configCall);
				
				$('#answerCmd').removeAttr('disabled');
				$('.callCmd').attr('disabled', 'true');
				showPanel();
				
				// ring phone
				ringTone.play();
			} else {
				// Reject the call if we are already in call.
				e.newSession.reject();
			}
			break;
		}
	}
};

var eventsSessionListener = function (e) {
	//$('#callStatus').val(e.type + ' : ' + e.description);
	switch (e.type) {
		case 'i_ao_request' : {
			if (e.session === callSession) {
				var code = e.getSipResponseCode();
				if (code == 180 || code == 183) {
					$('#callStatus').val('Sonnerie ...');
					ringBackTone.play();
				}
			}
			break;
		}
		case 'm_stream_audio_local_added' : {
			if (e.session === callSession) {
				$('#callStatus').val('Veuillez patienter ...');
			}
			break;
		}
		case 'm_stream_audio_remote_added', 'connecting', 'connected' : {
			if (e.session === callSession) {
				stopRinging();
				$('#callStatus').val('En appel');
				//$('#fullScreenCmd').removeAttr('disabled');
				showPanel();
			}
			break;
		}
		case 'terminating' : case 'terminated' : {
			if (e.session === callSession) {
				stopRinging();
				$('#callStatus').val('Appel terminé');
				$('#hangupCmd').attr('disabled', 'true');
				$('#answerCmd').attr('disabled', 'true');
				//$('#fullScreenCmd').attr('disabled', 'true');
				$('.callCmd').removeAttr('disabled');
				document.getElementById('popupIncomingCall').hidePopup();
				removeSrcMultimedia();
				callSession = null;
			}
			break;
		}
	}
};

function stopRinging() {
	ringBackTone.pause();
	ringTone.pause();
	ringBackTone.currentTime = 0;
	ringTone.currentTime = 0;
};

function login() {
	sipStack = new SIPml.Stack({
		realm : sipServerAddress,
		impi : "alice",
		impu : "sip:alice@" + sipServerAddress,
		password : "alice",
		display_name : "Alice",
		websocket_proxy_url : 'ws://' + sipServerAddress + ':10060',
		outbound_proxy_url : 'udp://' + sipServerAddress + ':5060',
		ice_servers : [],
		enable_rtcweb_breaker : true,
		enable_early_ims : true,
		events_listener : { events : '*', listener : eventsListener }
	});
	sipStack.start();
};

function logout() {
	if (sipStack) {
		sipStack.stop();
		sipStack = null;
	}
};

function call(type) {
	if (sipStack && !callSession) {
		var n = document.getElementById('contacts').selectedItem.id;
		var number = 'sip:' + n + '@' + sipServerAddress;
		callSession = sipStack.newSession(type, configCall);
		callSession.call(number, configCall);
	}
};

function hangup() {
	if (callSession) {
		callSession.hangup({
			events_listener : { events : '*', listener : eventsSessionListener }
		});
	}
};

function answer() {
	if (callSession) {
		callSession.accept(configCall);
		$('#answerCmd').attr('disabled', 'true');
	}
};

/** S'enregistrer auprès du serveur SIP */
function register() {
	session = sipStack.newSession('register', {
		expires: 300,  // send REGISTER every 5 minutes (300 secondes)
		events_listener: { events: '*', listener: eventsListener },
		sip_caps: [
			{ name: '+g.oma.sip-im', value: null },
			{ name: '+audio', value: null },
			{ name: 'language', value: '\"en,fr\"' }
		]
	});
	session.register();
};

function removeSrcMultimedia() {
	$('.multimedia').removeAttr('src');
};

function showPanel() {
	document.getElementById('popupIncomingCall').openPopupAtScreen(200, 200, false);
};

function toggleFullScreen() {
	var remoteVideo = document.getElementById('remoteVideo');
	if (!fullScreen) {
		remoteVideo.mozRequestFullScreen();
		$('#fullScreenBtn').attr('label', 'Quitter');
	} else {
		window.document.mozCancelFullScreen();
		$('#fullScreenBtn').attr('label', 'Plein écran');
	}
	fullScreen = !fullScreen;
};
